import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Not, In, Like } from 'typeorm';
import { Injectable } from '@nestjs/common';
import { ResultData } from 'src/common/utils/result';
import { CreateSchoolDto, UpdateSchoolDto, QuerySchoolDto } from './dto/school.dto';
import { SchoolEntity } from './entities/school.entity';

@Injectable()
export class SchoolService {
  constructor(
    @InjectRepository(SchoolEntity)
    private readonly schoolEntityRep: Repository<SchoolEntity>,
  ) {}
  async create(createSchoolDto: CreateSchoolDto) {
    const res = await this.schoolEntityRep.save(createSchoolDto);
    return ResultData.ok(res);
  }

  async findAll(query: QuerySchoolDto) {
    const entity = this.schoolEntityRep.createQueryBuilder('entity');
    entity.where({ delFlag: '0' });
    if (query.params) {
      entity.andWhere('entity.createTime BETWEEN :start AND :end', { start: query.params.beginTime, end: query.params.endTime });
    }
    if (query.schoolCode) {
      entity.andWhere('entity.schoolCode = :schoolCode', { schoolCode: query.schoolCode });
    }
    if (query.contactName) {
      entity.andWhere('entity.contactName LIKE :contactName', { contactName: `%${query.contactName}%` });
    }
    if (query.contactPhone) {
      entity.andWhere('entity.contactPhone = :contactPhone', { contactPhone: query.contactPhone });
    }
    if (query.schoolName) {
      entity.andWhere('entity.schoolName LIKE :schoolName', { schoolName: `%${query.schoolName}%` });
    }
    if (query.orderByColumn && query.isAsc) {
      const key = query.isAsc === 'ascending' ? 'ASC' : 'DESC';
      entity.orderBy(`entity.${query.orderByColumn}`, key);
    }

    // 如果没有分页参数则返回所有数据
    if (!query.pageSize || !query.pageNum) {
      const list = await entity.getMany();
      return ResultData.ok(list);
    }

    entity.skip(query.pageSize * (query.pageNum - 1)).take(query.pageSize);
    const [list, total] = await entity.getManyAndCount();

    return ResultData.ok({
      list,
      total,
    });
  }

  async findOne(id: number) {
    const res = await this.schoolEntityRep.findOne({
      where: {
        delFlag: '0',
        schoolId: id,
      },
    });
    return ResultData.ok(res);
  }

  async update(updateSchoolDto: UpdateSchoolDto) {
    const res = await this.schoolEntityRep.update({ schoolId: updateSchoolDto.schoolId }, updateSchoolDto);
    return ResultData.ok({ value: res.affected >= 1 });
  }

  async remove(schoolIds: number[]) {
    const res = await this.schoolEntityRep.update(
      { schoolId: In(schoolIds) },
      {
        delFlag: '1',
      },
    );
    return ResultData.ok({ value: res.affected >= 1 });
  }
}
